package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;


@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> pageQuery(Integer page, Integer rows, String key) {

        IPage<Brand> iPage = new Page<>(page, rows);

        Boolean condition = StringUtils.isNotBlank(key);
        //分页查询，自动回填结果
        //select * from tb_brand [where name like %key% or letter = key] limit x,y;
        //只有condition为true，like条件才会出现在sql中
        page(iPage,new QueryWrapper<Brand>()
                .like(condition,"name",key)
                .or()
                .eq(condition,"letter",key)
        );

        //封装PageDTO返回Brand的查询结果
        return new PageDTO<>(iPage.getTotal(), iPage.getPages(), BrandDTO.convertEntityList(iPage.getRecords()));
    }

    @Override
    public BrandDTO queryBrandById(Long id) {
        return new BrandDTO(getById(id));
    }

    @Override
    @Transactional
    public void addBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存brand并回显id
        save(brand);

        //保存中间表
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());
    }

    private void saveCategoryBrand(List<Long> categoryIds, Long id) {
        List<CategoryBrand> categoryBrands = categoryIds
                .stream()
                .map(cid -> CategoryBrand.of(cid, id))
                .collect(Collectors.toList());

        this.categoryBrandService.saveBatch(categoryBrands);
    }

    @Override
    @Transactional
    public void updateBrand(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        //保存brand并回显id
        updateById(brand);

        //中间表？？

        //先清理之前的关连关系
        //delete from tb_category_brand where brand_id =  #{id}
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id", brand.getId()));


        //重建分类和品牌的关系
        saveCategoryBrand(brandDTO.getCategoryIds(), brand.getId());

    }

    @Override
    @Transactional
    public void deleteById(Long id) {
        //TODO 什么样的品牌才能被删除，不满足条件的一定不能删除（有人用）

        removeById(id);

        //根据id删除中间表信息
        this.categoryBrandService.remove(new QueryWrapper<CategoryBrand>().eq("brand_id",id));
    }

    @Override
    public List<BrandDTO> listBrandByIds(List<Long> ids) {

        return BrandDTO.convertEntityList(listByIds(ids));
    }
}